package com.xiaoq.users.service;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xiaoq.AbstractReceiver;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.users.emchat.api.IMUserAPI;
import com.xiaoq.users.emchat.comm.ClientContext;
import com.xiaoq.users.emchat.comm.EasemobRestAPIFactory;
import com.xiaoq.users.emchat.comm.body.IMUserBody;
import com.xiaoq.users.emchat.comm.body.ResetPasswordBody;
import com.xiaoq.users.emchat.comm.wrapper.BodyWrapper;

@Component
public class IMUserReceiver extends AbstractReceiver {
	private static final Logger LOG = LoggerFactory.getLogger(IMUserReceiver.class);
	private static final String LOG_PREFIX = "[IM] [SMS] [QUEUE] ";

	public void execute(String message) {
		LOG.info(MessageFormat.format(LOG_PREFIX + "收到消息, {0}", message));
		IMUserTaskVo task = null;
		try {
			task = JsonUtil.asObject(message, IMUserTaskVo.class);
		} catch (Exception e) {
			String msg = LOG_PREFIX + "消息解析错误";
			LOG.error(msg, e);
			throw new RuntimeException(msg, e);
		}

		LOG.info(LOG_PREFIX + "消息解析完毕");

		switch (task.getAction()) {
		case CREATE_SINGLE:
			createSingle(task);
			break;
		case RESET_PASSWD:
			resetPasswd(task);
			break;
		default:
			break;
		}

		LOG.info(LOG_PREFIX + "接收消息处理完毕");
	}

	private void resetPasswd(IMUserTaskVo task) {
		EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
				.getAPIFactory();
		IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		BodyWrapper pwdBody = new ResetPasswordBody(task.getPasswd());
		user.modifyIMUserPasswordWithAdminToken(task.getId(), pwdBody);

	}

	private void createSingle(IMUserTaskVo task) {
		EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
				.getAPIFactory();
		IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		BodyWrapper userBody = new IMUserBody(task.getId(), task.getPasswd(), task.getNickName());
		Object obj = user.createNewIMUserSingle(userBody);
		if (null != obj) {
			LOG.info("注册IM用户[单个]: " + obj.toString());
		}
	}
}